package com.whut.whw.search;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.find.GoodsEntity;
import com.whut.whw.find.MyGoodsListAdapter;
import com.whut.whw.personalinfo.mythings.FinishFragment;
import com.whut.whw.personalinfo.mythings.PushFragment;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.whut.whw.R.id.mythings_viewpager;
import static com.whut.whw.util.Utils.getContext;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/22
 *     desc   : 搜索Activity
 *     version: 1.0
 * </pre>
 */
public class SearchActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tl_search_tab)
    TabLayout mTab;
    @BindView(R.id.vp_search_result)
    ViewPager mViewPager;
    @BindView(R.id.ll_search_hot)
    LinearLayout mLlHot;
    @BindView(R.id.ll_search_result)
    LinearLayout mLlResult;
    @BindView(R.id.fl_search_hotLabels)
    FlowLayout mFlHotLabels;

    private static final String TAG = "SearchActivity";
    private SearchView mSearchView;
    private SearchView.SearchAutoComplete mSearchAutoComplete;
    private FragmentPagerAdapter mAdapter;
    private SearchTabFragment[] fragments;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initToolbar();
        initHot();
        initViewPager();
        initTabLayout();

        mLlHot.setVisibility(View.VISIBLE);
        mLlResult.setVisibility(View.INVISIBLE);
    }



    /**
     * 初始化toolbar
     */
    private void initToolbar() {
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setTitle(R.string.search_title);
        // 设置返回图标
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);

    }

    private void initViewPager() {
       fragments = new SearchTabFragment[]{
                SearchTabFragment.newInstance(getResources().getString(R.string.search_tab1)),
                SearchTabFragment.newInstance(getResources().getString(R.string.search_tab1))
        };
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        };
        mViewPager.setAdapter(mAdapter);
    }

    private void initTabLayout() {
        mTab.setupWithViewPager(mViewPager);//绑定viewpager，使之可联动
        mTab.getTabAt(0).setText(getResources().getString(R.string.search_tab1));
        mTab.getTabAt(1).setText(getResources().getString(R.string.search_tab2));
    }

    /**
     * 初始化热门搜索
     */
    private void initHot() {
        String[] mVals = {"工作", "学习ing哈哈", "夏至未至", "我是攻城狮攻城狮无敌工程师", "吹风机", "双桶洗衣机不刀", "楚乔传", "日系男神柏原崇"};
        for (int i = 0; i < mVals.length; i++) {
            LayoutInflater mInflater = getLayoutInflater().from(context);
            TextView tv = (TextView) mInflater.inflate(
                    R.layout.textview_search_label, mFlHotLabels, false);
            tv.setText(mVals[i]);
            final String str = tv.getText().toString();
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    searchLabel(str);
                    mSearchAutoComplete.setText(str);
                    getSearchResult(str);
                }
            });
            mFlHotLabels.addView(tv);//添加到父View
        }

    }


    @Override
    public void setListener() {
        // 设置返回图标的监听事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if (mSearchAutoComplete.isShown()) {
                    try {
                        mSearchAutoComplete.setText("");
                        Method method = mSearchView.getClass().getDeclaredMethod("onCloseClicked");
                        method.setAccessible(true);
                        method.invoke(mSearchView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    finish();
                }*/
                finish();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_search_nav_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.search_activity_nav_search);
        LogUtils.d(TAG, searchItem == null);

        //通过MenuItem得到SearchView
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        mSearchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);
//        搜索框提示文字
        mSearchView.setQueryHint("寻找好物");

        //设置输入框提示文字样式
        mSearchAutoComplete.setHintTextColor(ContextCompat.getColor(context, android.R.color.darker_gray));
        mSearchAutoComplete.setTextColor(ContextCompat.getColor(context, android.R.color.background_light));
        // 设置输入框字体大小
        mSearchAutoComplete.setTextSize(16);
        //设置触发查询的最少字符数（默认2个字符才会触发查询）
//        mSearchAutoComplete.setThreshold(1);

        //设置搜索框有字时显示叉叉，无字时隐藏叉叉
        mSearchView.onActionViewExpanded();
//        mSearchView.setIconified(true);
        // 设置SearchView默认展开搜索框
        mSearchView.setIconified(false);

        //修改搜索框控件间的间隔（这样只是为了更加接近网易云音乐的搜索框）
        LinearLayout search_edit_frame = (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) search_edit_frame.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        search_edit_frame.setLayoutParams(params);
        // 点击软键盘上的搜索按钮
        mSearchAutoComplete.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //实现自己的搜索逻辑
                    getSearchResult(mSearchAutoComplete.getText().toString());
                    return true;
                }
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 点击搜索按钮，得到搜索结果，将结果填充在界面上
     */
    private void getSearchResult(String keyWord) {
        /**
         * ....
         */
        // 先隐藏键盘
        ((InputMethodManager) mSearchAutoComplete.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(
                        SearchActivity.this
                                .getCurrentFocus()
                                .getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);

        // 将热门搜索设置为不可见，获取查询结果列表
        mLlHot.setVisibility(View.INVISIBLE);
        mLlResult.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 一定要有两个不同的数据集合
                List<GoodsEntity> list = getData();
                List<GoodsEntity> list2 = getData();
                fragments[0].refreshData(list);
                fragments[1].refreshData(list2);
            }
        }, 1000);
        ToastUtils.showShort("搜索：" + keyWord);
    }


    // 让菜单同时显示图标和文字
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private List<GoodsEntity> getData() {
        List<GoodsEntity> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray();
            for (int i = 0; i < 3; i++) {
                JSONObject obj = new JSONObject();

                obj.put("headImg", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg");

                obj.put("mainImgUrl", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg");
                obj.put("name", "包美丽Y" + i);
                obj.put("address", "河北张家口" + i);
                obj.put("publishTime", "2017-06-1" + i);
                obj.put("price", "¥20");
                obj.put("title", "书籍便宜专卖啦啦啦");
                obj.put("description", "“淘气”就是那闹事的猫。它在东皇城根穷人家里，原叫做‘小黑’。李太太嫌‘小 \n" +
                        "黑’的称谓太俗，又笑说：“那跟门房‘老白’不成了一对儿么？老白听了要生气的”。猫 \n" +
                        "送到城南长街李家那天，李太太正在请朋友们茶会，来客都想给它起个好听的名字。一个爱 \n" +
                        "慕李太太的诗人说“：在西洋文艺复兴的时候，标准美人都要生得黑，我们读莎士比亚和法 \n" +
                        "国七星派诗人的十四行诗，就知道使他们颠倒的都是些黑美人。");
                obj.put("commentCount", 100 + 10 * i);
                obj.put("likeCount", 230);
                obj.put("wantCount", 8532);
                array.put(obj);
            }
            LogUtils.d(TAG, array.toString());
            Gson gson = new Gson();
            list = gson.fromJson(array.toString(), new TypeToken<List<GoodsEntity>>() {
            }.getType());
            LogUtils.d(TAG, list.size());
            for (int i = 0; i < list.size(); i++) {
                LogUtils.d(TAG, list.get(i).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return list;
    }

}
